<?php
declare(strict_types=1);

namespace App\Event;

use App\Model\User;
use App\Model\Menus;
use Jenssegers\Agent\Agent;
use Hyperf\HttpServer\Contract\RequestInterface;

class OperationLogEvent
{
    /**
     * @var User
     */
    public $user;

    /**
     * 请求日志数据
     *
     * @var array
     */
    public $logdata;

    /**
     * OperationLogEvent constructor.
     *
     * @param RequestInterface $request
     * @param User             $user
     */
    public function __construct(RequestInterface $request, User $user,string $allow = '未知操作')
    {
        $this->user = $user;
        $serverParams = $request->getServerParams();
        $arguments = $request->all();
        if (isset($arguments['password'])) unset($arguments['password']);
        $userId = $this->user->id;
        $uuid = getCookie('HYPERF_SESSION_ID');
        $url = trim($request->fullUrl(),'?');
        $agent = new Agent();
        $agent->setUserAgent($request->getHeaderLine('user-agent')?:'');
        $ip = $request->getHeaderLine('x-real-ip')?:$request->getHeaderLine('x-forwarded-for')?:$request->getServerParams()['remote_addr'] ?? '';
        // ip转换地域
        if($ip && ip2long($ip) != false){
            $location = getIpLocation($ip);
            $cityId = $location['city_id']??0;
        }else{
            $cityId = 0;
        }
        $request_uri = trim(($serverParams['request_uri']??''),'/');
        $this->logdata =  [
            'type' => ($request_uri == 'sso/login')?'login':'operate',/*日志类型*/
            'operation_name' => Menus::where([['apiurl','like','%'.$request_uri.'%']])->value('title')?:$allow,/*操作名*/
            'server_name' => $request->getHeaderLine('host')?:'',
            'server_addr' => getServerLocalIp()??'',/*内网IP地址*/
            'remote_addr' => $serverParams['remote_addr']??'',/*客户端IP，负载均衡该值有影响*/
            'forwarded_for' => $request->getHeaderLine('x-forwarded-for')?:'',
            'real_ip' => $ip,/*真实IP*/
            'city_id' => $cityId,/*城市id*/
            'user_agent' => $request->getHeaderLine('user-agent')?:'',/*浏览器标识*/
            'platform' => $agent->platform()??'',/*平台（操作系统）*/
            'device' => $agent->device()??'',/*设备*/
            'browser' => $agent->browser()??'',/*浏览器*/
            'url' => $url,/*请求地址*/
            'uri' => $request_uri,/*请求路径*/
            'arguments' => $arguments?json_encode($arguments):'',/*请求参数*/
            'method' => $serverParams['request_method']??'',/*请求类型*/
        //     'execution_time' => $executionTime,
        //     'request_body_size' => $requestHeaders['content-length'][0]??'',
        //     'response_body_size' => $rbs,
            'uuid' => $uuid,/*通用唯一标识符，uv*/
            'user_id' => $userId?:0,/*访问用户*/
            'mid' => $this->user->mid?:0,/*访问用户*/
            'referer' => $request->getHeaderLine('referer')?:'',/*来源*/
            'unix_time' => $serverParams['request_time']??'',/*访问时间*/
        ];
    }
}
